from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qwt5 import *

import logging
import logger_config
from data_model import *

VOLTAGE_PEN = QPen(QBrush(QColor(255, 0, 0)), 0)
VOLTAGE2_PEN = QPen(QBrush(QColor(0, 0, 127)), 0)
CURRENT_PEN = QPen(QBrush(QColor(0, 127, 0)), 0)
TEMPERATURE_PEN = QPen(QBrush(QColor(0, 0, 255)), 0)

TEMP_MIN, TEMP_MAX = 20, 70

class QwtHandler(object):
	def __init__(self, window, graph, graph2, is_36):
		self.window = window
		global U_MIN, U_MAX, I_MIN, I_MAX
		if is_36:
			U_MIN, U_MAX = 20, 50
			I_MIN, I_MAX = -40, 40
		else:
			U_MIN, U_MAX = 6, 17
			I_MIN, I_MAX = -100, 100
		self.graphs = self.graph, self.graph2 = graph, graph2  

		# curves
		self.voltage_curve = QwtPlotCurve("Feszültség")
		self.voltage2_curve = QwtPlotCurve("Feszültség2")
		self.current_curve = QwtPlotCurve("Áramerősség")
		self.temperature_curve = QwtPlotCurve("Hőmérséklet")

		for curve, pen, graph in [
			(self.voltage_curve, VOLTAGE_PEN, self.graph),
			(self.voltage2_curve, VOLTAGE2_PEN, self.graph),
			(self.current_curve, CURRENT_PEN, self.graph2),
			(self.temperature_curve, TEMPERATURE_PEN, self.graph2),
		]:
			curve.setPen(pen)
			curve.attach(graph)
			curve.setRenderHint(QwtPlotItem.RenderAntialiased)

		#self.voltage2_curve.setYAxis(QwtPlot.yRight)
		self.temperature_curve.setYAxis(QwtPlot.yRight)

		#self.voltage_curve.setData(xs, ys)

		self.graph.enableAxis(QwtPlot.yRight)
		self.graph2.enableAxis(QwtPlot.yRight)

		self.graph.insertLegend(Qwt.QwtLegend(), Qwt.QwtPlot.TopLegend)
		self.graph2.insertLegend(Qwt.QwtLegend(), Qwt.QwtPlot.TopLegend)

		# grids and some markers
		for g in self.graphs:
			grid = QwtPlotGrid()
			grid.enableXMin(True)
			grid.enableYMin(True)
			grid.setMajPen(QPen(Qt.gray, 0, Qt.SolidLine))
			grid.setMinPen(QPen(Qt.gray, 0, Qt.DotLine))
			grid.attach(g)

			marker = QwtPlotMarker()
			marker.setXValue(0)
			marker.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
			marker.setLineStyle(Qwt.QwtPlotMarker.VLine)
			marker.attach(g)

		# zoomers
		self.zoomer = QwtPlotZoomer(QwtPlot.xBottom,
			QwtPlot.yLeft,
			QwtPicker.DragSelection,
			QwtPicker.AlwaysOff,
			self.graph.canvas())
		self.zoomer_2 = QwtPlotZoomer(QwtPlot.xTop,
			QwtPlot.yRight,
			QwtPicker.DragSelection,
			QwtPicker.AlwaysOff,
			self.graph.canvas())
		self.zoomer2 = QwtPlotZoomer(QwtPlot.xBottom,
			QwtPlot.yLeft,
			QwtPicker.DragSelection,
			QwtPicker.AlwaysOff,
			self.graph2.canvas())
		self.zoomer2_2 = QwtPlotZoomer(QwtPlot.xTop,
			QwtPlot.yRight,
			QwtPicker.DragSelection,
			QwtPicker.AlwaysOff,
			self.graph2.canvas())

		self.zoomer.zoomed.connect(self.zoomed)
		self.zoomer2.zoomed.connect(self.zoomed)

		self.panner = QwtPlotPanner(self.graph.canvas())
		self.panner2 = QwtPlotPanner(self.graph2.canvas())

		for p in (self.panner, self.panner2):
			p.setMouseButton(Qt.LeftButton, Qt.ShiftModifier)
			p.panned.connect(self.panner_moved)

		for z in (self.zoomer, self.zoomer_2, self.zoomer2, self.zoomer2_2):
			z.setMousePattern(QwtEventPattern.MouseSelect3, Qt.LeftButton, Qt.AltModifier)
			z.setMousePattern(QwtEventPattern.MouseSelect6, Qt.RightButton, Qt.AltModifier)
		self.resize_scaledraw()
		
	def panner_moved(self, dx, dy):
		# other = (self.panner2 if self.window.sender() == self.panner else self.panner)
		other = self.window.sender() == self.panner and self.panner2 or self.panner
		other.moveCanvas(dx, 0)
		self.resize_scaledraw()

	def resize_scaledraw(self):
		extent = 0
		for y_axis in [QwtPlot.yLeft, QwtPlot.yRight]:
			for g in self.graphs:
				sd = g.axisScaleDraw(y_axis)
				sd.setMinimumExtent(0)
				extent = max(extent, sd.extent(QPen(), g.axisFont(y_axis)))
			for g in self.graphs:
				g.axisScaleDraw(y_axis).setMinimumExtent(extent)
		self.graph.updateLayout()
		self.graph2.updateLayout()

	marker = None
	marker2 = None
	
	def clear_markers(self):
		if self.marker: self.marker.detach()
		if self.marker2: self.marker2.detach()

	
	def set_markers(self, cycle_len):
		for m, g in [('marker', self.graph), ('marker2', self.graph2)]:
			marker = QwtPlotMarker()
			marker.setXValue(cycle_len)
			marker.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
			marker.setLineStyle(Qwt.QwtPlotMarker.VLine)
			marker.attach(g)
			setattr(self, m, marker)
			
	def refresh_graph(self, time_data, voltage_data, voltage2_data, current_data, temperature_data):
		#self.graph.clear()
		#self.graph2.clear()
		self.voltage_curve.setData(time_data, voltage_data)
		self.voltage2_curve.setData(time_data, voltage2_data)
		self.current_curve.setData(time_data, current_data)
		self.temperature_curve.setData(time_data, temperature_data)
		self.graph.replot()
		self.graph2.replot()
		
	def zoomed(self, rect):
		def adjust_zoomer(z):
			rect2 = z.zoomRect()
			rect2.setLeft(rect.left())
			rect2.setRight(rect.right())
			z.zoom(rect2)

		if self.window.sender() == self.zoomer:
			self.graph2.setAxisScale(QwtPlot.xBottom, rect.left(), rect.right())
			adjust_zoomer(self.zoomer2)
			adjust_zoomer(self.zoomer2_2)
			#self.zoomer_2.zoom(self.zoomer.zoomRect())
			self.graph2.replot()
		elif self.window.sender() == self.zoomer2:
			self.graph.setAxisScale(QwtPlot.xBottom, rect.left(), rect.right())
			adjust_zoomer(self.zoomer)
			adjust_zoomer(self.zoomer_2)
			#self.zoomer.zoom(self.zoomer_2.zoomRect())
			self.graph.replot()
		else:
			logging.error("Cannot determine which zoomer fired the event")

		self.resize_scaledraw()

	
	def reset_scales(self, time_scale, t_max):
		rect = QRectF(); rect.setTop(U_MAX); rect.setLeft(-OVERLAP_INTERVAL / time_scale); rect.setBottom(U_MIN); rect.setRight(t_max / time_scale)
		self.zoomer.setZoomBase(rect.normalized())
		self.zoomer_2.setZoomBase(rect.normalized())

		rect.setBottom(I_MIN);rect.setTop(I_MAX)
		self.zoomer2.setZoomBase(rect.normalized())

		rect.setBottom(TEMP_MIN);rect.setTop(TEMP_MAX)
		self.zoomer2_2.setZoomBase(rect.normalized())

		#self.zoomer.zoom()
		for g in self.graphs:
			for a in (QwtPlot.xBottom, QwtPlot.xTop):
				g.setAxisScale(a, -OVERLAP_INTERVAL / time_scale, t_max / time_scale)

		self.graph.setAxisTitle(QwtPlot.xBottom, "Idő ({})".format({1: 'sec', 60: 'min', 3600: 'h'}[time_scale]))
		self.graph.setAxisScale(QwtPlot.yLeft, U_MIN, U_MAX)
		self.graph.setAxisScale(QwtPlot.yRight, U_MIN, U_MAX)

		self.graph2.setAxisScale(QwtPlot.yLeft, I_MIN, I_MAX)
		self.graph2.setAxisScale(QwtPlot.yRight, TEMP_MIN, TEMP_MAX)
